﻿package com.diligreat.util;
import java.security.*;
//import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Base64;
import org.bouncycastle.util.encoders.Hex;


/**
 * @comments
 * @author zg
 * @date 2011-10-25
 */
public class EncryptUtil{
	
	private static final String  ALGORITHM = "HmacSHA224";
	private static final String  ENCODEING = "UTF-8";
	
	//private static byte[] key = Base64.decode(Constants.ENCRYPT_KEY);
	//private static SecretKey secretKey = new SecretKeySpec(key,ALGORITHM);
	//private static Mac mac;

	static{
		Security.addProvider(new BouncyCastleProvider());
	}
	
	/**
	 * 对字符串进行加密
	 * @param text 明文
	 * @return 密文
	 * @throws NoSuchAlgorithmException 
	 * @throws InvalidKeyException 
	 */
	public static String encode(String text) throws Exception {
		byte[] key = Base64.decode(Constants.ENCRYPT_KEY);
		SecretKey secretKey = new SecretKeySpec(key,ALGORITHM);
		Mac mac = Mac.getInstance(secretKey.getAlgorithm());
		mac.init(secretKey);
		byte[] codedText = mac.doFinal(text.getBytes(ENCODEING));
		return new String(Hex.encode(codedText),ENCODEING);
	}
	
	//////////////////////////////////////////////////////////////////////////
	
	/*private static String initHmacSHA224Key() throws Exception{
		//初始化key
		Security.addProvider(new BouncyCastleProvider());
		KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
		SecretKey secrttKey = keyGenerator.generateKey();
		byte[] keyEncode = secrttKey.getEncoded();
		byte[] base64Key =  Base64.encode(keyEncode);
		return new String(base64Key,ENCODEING);
	}*/
	
/*	public static void main(String[] args) throws Exception{

		System.out.println(EncryptUtil.encode("admin"));
	}*/
}
